<template>
  <div class="mainos">
    <div class="main_spac1" style="padding-bottom: 5px">
      <div class="main_white padding10">
        <el-form
          :inline="true"
          :rules="rules"
          :model="monitorForm"
          class="demo-form-inline marginTop0"
          ref="userListFrom"
          label-width="60px"
        >
          <div class="main_crumbs boxdq">
            <div class="main_crumbs_l">
              <a href="javascript:;" @click="$router.back(-1)">
                <i class="el-icon-arrow-down"></i>返回
              </a>
              <em>|</em>
              <span>订单退货</span>
            </div>
          </div>
          <div class="main_tile boxdq marginTop10">
            <div class="main_tile_l marginLeft0"><em></em>基础信息</div>
          </div>
          <div class="main_xq afterbox">
            <ul class="boxha">
              <li>
                退货单号：<span>{{ info.order_sn }}</span>
              </li>
              <li>
                创建时间：<span>{{
                  parseTime(info.created_at, "{y}-{m}-{d}")
                }}</span>
              </li>
              <li>
                单据状态：<span>{{ order_status[info.status] }}</span>
              </li>
              <li>
                申请金额：<span>{{ info.apply_money }}</span>
              </li>
              <li>
                实退金额：<span>{{ info.real_money }}</span>
              </li>
              <li>
                用户名称：<span>{{ info.zid_info?info.nickname+"【"+info.zid_info.nickname+"】":info.nickname }}</span>
              </li>
              <li>
                关联订单：<span>{{
                  info.related_order_sn ? info.related_order_sn : ""
                }}</span>
              </li>
              <li>
                订单支付状态：<span>{{ pay_type[info.order_pay_status] }}</span>
              </li>
              <li>
                订单配送日期：<span>{{
                  info.order_send_time
                    ? parseTime(info.order_send_time, "{y}-{m}-{d}")
                    : ""
                }}</span>
              </li>
              <li>
                退货原因：<span>{{ info.return_remark }}</span>
              </li>
              <li>
                业务员：<span>{{ info.driver ? info.driver.name : "" }}</span>
              </li>
              <li>
                业务员手机：<span>{{ info.driver_mobile }}</span>
              </li>
              <li>
                司机：<span>{{ info.salesman ? info.salesman.name : "" }}</span>
              </li>
              <li>
                司机手机：<span>{{ info.salesman_mobile }}</span>
              </li>
            </ul>
          </div>

          <div class="main_tile boxdq marginTop15">
            <div class="main_tile_l marginLeft0"><em></em>商品详情</div>
          </div>

          <div class="main_table marginTop0">
            <el-table
              ref="multipleTable"
              :data="info.return_list"
              element-loading-text="加载中"
              fit
              border
              highlight-current-row
            >
              <el-table-column label="序号">
                <template slot-scope="scope">{{ scope.$index + 1 }}</template>
              </el-table-column>
              <el-table-column
                label="商品名称"
                prop="goods_name"
                class-name="main_hei"
              >
                <template slot-scope="scope"
                  >{{ scope.row.goods_name ? scope.row.goods_name : "" }}【{{
                    scope.row.spu_name
                  }}】</template
                >
              </el-table-column>
              <el-table-column label="单位" prop="unit" class-name="main_hei" />
              <el-table-column
                label="配送数量"
                prop="send_num"
                class-name="main_hei"
              />
              <el-table-column
                label="配送单价"
                prop="send_price"
                class-name="main_hei"
              />
              <el-table-column
                label="申请数量"
                prop="apply_num_copy"
                class-name="main_hei"
              >
                <template slot-scope="scope">{{
                  scope.row.apply_num_copy
                }}</template>
              </el-table-column>

              <el-table-column label="申请单价" prop="apply_price_copy" />

              <el-table-column label="申请金额" prop="apply_money_copy" />

              <el-table-column label="实退数量" width="160" prop="apply_num">
                <template slot-scope="scope">
                  <el-input
                    v-model.trim="scope.row.apply_num"
                    placeholder="退货数量"
                    class="wid110"
                    @change="numberChange($event, scope.$index, 1, scope)"
                  ></el-input>
                </template>
              </el-table-column>

              <el-table-column label="实退单价" width="160" prop="apply_price">
                <template slot-scope="scope">
                  <el-input
                    v-model.trim="scope.row.apply_price"
                    placeholder="实退单价"
                    class="wid110"
                    @change="numberChange($event, scope.$index, 2, scope)"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column width="160" label="实退金额" prop="apply_money">
                <template slot-scope="scope">
                  <!-- {{
                    (parseFloat(scope.row.apply_num) *
                      parseFloat(scope.row.apply_price))
                      | twoPlace
                  }} -->
                  <el-input
                    v-model.trim="scope.row.apply_money"
                    placeholder="实退金额"
                    class="wid110"
                    @change="numberChange($event, scope.$index, 4, scope)"
                  ></el-input>
                </template>
              </el-table-column>

              <el-table-column label="报损数量" width="160" prop="real_money">
                <template slot-scope="scope">
                  <el-input
                    v-model.trim="scope.row.report_spills_num"
                    placeholder="报损数量"
                    class="wid110"
                    @change="numberChange($event, scope.$index, 3, scope)"
                  ></el-input>
                </template>
              </el-table-column>

              <el-table-column label="成本单价" width="160" prop="inventory_price">
                <template slot-scope="scope">
                  <el-input
                    v-model.trim="scope.row.inventory_price"
                    placeholder="成本单价"
                    class="wid110"
                  ></el-input>
                </template>
              </el-table-column>

              <el-table-column label="备注" width="200" prop="remark" />
            </el-table>
          </div>

          <div class="main_tile boxdq marginTop10">
            <div class="main_tile_l marginLeft0"><em></em>其他</div>
          </div>
          <div class="main_xq">
            <ul class="boxha">
              <li class="main_w100">
                合计：<span>{{ total }}</span>
              </li>

              <div class="mainoe_up" style="min-height: 200px">
                <div class="main_tile boxdq marginBottom10">
                  <div class="main_tile_l marginLeft0">
                    <em></em>上传凭证
                    <span
                      >仅支持jpg，jpeg，png格式，文件小于2M，最多添加5张</span
                    >
                  </div>
                </div>
                <div class="main_upImg marginLeft10">
                  <el-upload
                    :action="uploadPath"
                    list-type="picture-card"
                    :on-success="handSuccess"
                    :on-remove="handleRemove"
                    :limit="5"
                    :file-list="filelist"
                    :on-exceed="handleExceed"
                    :before-upload="beforeAvatarUpload"
                    :headers="{
                      Authorization: getToken()
                    }"
                    multiple
                  >
                    <span slot="default">
                      <svg
                        aria-hidden="true"
                        class="main_page_svg"
                        width="32"
                        height="27"
                      >
                        <use xlink:href="#icon-commodit_camera" />
                      </svg>
                    </span>
                  </el-upload>

                  <el-dialog :visible.sync="dialogVisible">
                    <img :src="dialogImageUrl" alt />
                  </el-dialog>
                  <div class="clearfix"></div>
                </div>
              </div>
            </ul>
          </div>
        </el-form>
        <div class="clearfix"></div>
        <div class="newConBox_p200 paddingBottom10" id="newConBox">
          <div class="newConBox_h32">
            <div
              :class="['mainor_pr boxdq newConBox ', { on: searchBarFixed }]"
            >
              <div class="mainor_prl">
                <el-button type="primary" @click="reject" v-repeatClick
                  >驳回</el-button
                >
                <el-button @click="pass">通过</el-button>
                <el-button @click="$router.back(-1)">取消</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { return_order_info, return_order_check } from "@/api/order/orderReturn";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import rules from "@/rules/financial/financialRecharge_record";
import { parseTime } from "@/utils/index";
import { puzzleImg } from "@/api/currency";
import { uploadPath } from "@/api/currency";

export default {
  computed: {
    ...mapGetters(["avatar"]),
    total() {
      let sz = 0;
      this.info.return_list.forEach(item => {
        let count = parseFloat(this.$toFixed(parseFloat(item.apply_money)));
        sz += count;
      });
      return sz ? this.$toFixed(sz) : 0;
    }
  },
  components: {},
  watch: {},
  data() {
    return {
      // 验证
      rules,
      // 时间
      parseTime,
      uploadPath,
      // 基本信息
      info: {
        return_list: [],
        pics: []
      },
      logs: [],
      order_status: [],
      pay_type: [],
      statusList: [],
      puzzleImg,
      listLoading: false,
      filelist: [],
      id: this.$route.params.id,
      // 监听滚动
      searchBarFixed: false,
      isEdit: false,
      // 图片预览
      srcList: [],
      // 上传图片
      dialogImageUrl: "",
      dialogVisible: false,
      monitorForm: {
        form: {
          id: "",
          pics: [],
          reject_remark: "",
          list: [],
          status: ""
        }
      },
      return_remark_list: ["菜品变质", "菜品损坏"]
    };
  },

  created() {
    this.return_order_info();
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  beforeRouteLeave(to, from, next) {
    if (this.isEdit) {
      setTimeout(() => {
        this.$confirm(
          "您已经有数据操作，离开页面系统不会保存您的操作，确定离开吗？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
          .then(() => {
            // 正常跳转
            next();
          })
          .catch(() => {
            next(false);
          });
      }, 200);
    } else {
      next();
    }
  },
  methods: {
    // 监听滚动
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      scrollTop + document.documentElement.clientHeight >
      document.getElementById("newConBox").offsetTop + 300
        ? (this.searchBarFixed = false)
        : (this.searchBarFixed = true);
    },
    // 监听输入
    numberChange(val, index, type, scope) {
      let list = this.info.return_list;
      if (!/^(\d+\.?)?\d{0,2}$/.test(val)) {
        this.$message.error("请输入整数和两位小数");
        if (type == 1) {
          list[index].apply_num = list[index].apply_num_copy;
        } else {
          list[index].apply_price = list[index].apply_price_copy;
        }
        return;
      }
      this.isEdit = true;
      switch (type) {
        case 1:
          if (val <= parseFloat(list[index].apply_num_copy)) {
            list[index].apply_num = parseFloat(val);
          } else {
            list[index].apply_num = parseFloat(list[index].apply_num_copy);
          }
          if (scope.row.apply_price && val != null && val != "") {
            scope.row.apply_money = this.$toFixed(
              parseFloat(scope.row.apply_price) *
                parseFloat(scope.row.apply_num)
            );
          }
          break;
        case 2:
          if (scope.row.apply_num && val != null && val != "") {
            scope.row.apply_money = this.$toFixed(
              parseFloat(scope.row.apply_price) *
                parseFloat(scope.row.apply_num)
            );
          }
          break;
      }
    },
    return_order_info() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: this.id })) +
              apiUrl().appsecret
          )
        },
        apiUrl().name,
        { id: this.id }
      );
      return_order_info(data).then(res => {
        console.log(res);
        if (res.errcode == 0) {
          let arry = [];
          res.data.info.pics = JSON.parse(res.data.info.pics);
          if (res.data.info.pics.length > 0) {
            res.data.info.pics.forEach((a, index) => {
              a = this.avatar.domain + a;
              arry.push({
                name: "",
                path: "",
                url: a,
                id: index
              });
            });
          }
          this.filelist = JSON.parse(JSON.stringify(arry));
          let remark = res.data.info.return_remark;
          let index = this.return_remark_list.indexOf(remark);
          if (res.data.info.return_list) {
            res.data.info.return_list.forEach(item => {
              item.apply_num_copy = item.apply_num;
              item.apply_money_copy = item.apply_money;
              item.apply_price_copy = item.apply_price;
              if (index == -1) {
                item.report_spills_num = 0;
              } else {
                item.report_spills_num =
                  parseFloat(item.apply_num) - parseFloat(item.real_num);
              }
            });
          }
          this.info = res.data.info;
          this.order_status = res.data.order_status;
          this.pay_type = res.data.pay_type;
          this.statusList = res.data.statusList;
          this.monitorForm.form.pics = res.data.info.pics;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 上传图片-删除
    handleRemove(file) {
      const i = this.monitorForm.form.pics.findIndex(
        item => item.path == file.path
      );
      this.monitorForm.form.pics.splice(i, 1);
    },
    // 上传图片-查看
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 5 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    beforeAvatarUpload(file) {
      let type = file.type;
      let typeList = ["image/jpeg", "image/jpg", "image/png"];
      let isType = false;
      typeList.forEach(e => {
        if (e == type) {
          isType = true;
          return;
        }
      });
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isType) {
        this.$message.error("请上传正确的图片格式");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isType && isLt2M;
    },

    // 上传图片-成功
    handSuccess(res, file, filelist) {
      this.isEdit = true;
      this.monitorForm.form.pics.push(res.data.path);
    },
    // 保存
    reject() {
      this.$prompt("驳回原因", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        customClass: "customClass"
      })
        .then(({ value }) => {
          this.isEdit = false;
          this.monitorForm.form.reject_remark = value;
          this.monitorForm.form.status = 4;
          this.save();
        })
        .catch(() => {});
    },
    pass() {
      this.isEdit = false;
      this.monitorForm.form.status = 1;
      this.save();
    },
    save() {
      this.info.return_list.forEach(item => {
        var obj = {
          id: item.id,
          real_num: item.apply_num,
          real_price: item.apply_price,
          real_money: item.apply_money,
          report_spills_num: item.report_spills_num,
          inventory_price:item.inventory_price
        };
        this.monitorForm.form.list.push(obj);
      });
      this.monitorForm.form.id = this.info.id;
      if (this.monitorForm.form.list) {
        this.monitorForm.form.list = JSON.stringify(this.monitorForm.form.list);
      }
      if (this.monitorForm.form.pics) {
        this.monitorForm.form.pics = JSON.stringify(this.monitorForm.form.pics);
      }
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          )
        },
        apiUrl().name,
        this.monitorForm.form
      );
      return_order_check(data).then(res => {
        if (res.errcode == 0) {
          this.$router.back(-1);
        } else if (res.errcode == 40035) {
          let msg = res.errmsg;
          this.$nextTick(() => {
            this.$alert(msg, "提示", {
              confirmButtonText: "确定",
              callback: action => {
                this.$router.back(-1);
              }
            });
          });
        } else {
          this.$message.error(res.msg);
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainos {
  .main_tile {
    .mainos_tile_r {
      color: $colour_red;
      font-size: $font_14;
    }
  }
  .newConBox.on {
    // margin-left: -10px;
    padding-left: 0px !important;
    width: 100% !important;
    margin-right: 20px;
    background-color: transparent;
  }
  .main_table {
    /deep/.el-table__body-wrapper {
      overflow-y: auto;
    }
    /deep/.el-checkbox {
      margin-bottom: 0;
    }
  }

  .main_xqs {
    width: 55%;
    display: block;
    text-align: left;
    /deep/.el-input--small {
      width: 100%;
    }
  }
  .main_table /deep/.el-table--small td .cell {
    height: 40px !important;
    line-height: 40px !important;
  }
  /deep/.el-form-item {
    margin-bottom: 0 !important;
  }
  .main_xq {
    ul {
      li {
        .main_xqi_i {
          position: relative;
          width: 120px;
          overflow: hidden;
          /deep/.el-upload-list__item-status-label {
            position: absolute;
            right: -15px;
            top: -6px;
            z-index: 91;
            width: 40px;
            height: 24px;
            background: #13ce66;
            text-align: center;
            -webkit-transform: rotate(45deg);
            transform: rotate(45deg);
            -webkit-box-shadow: 0 0 1pc 1px rgba(0, 0, 0, 0.2);
            box-shadow: 0 0 1pc 1px rgba(0, 0, 0, 0.2);
            display: block;
            i {
              font-size: $font_12;
              margin-top: 11px;
              color: $white;
              -webkit-transform: rotate(-45deg);
              transform: rotate(-45deg);
            }
          }
        }
        /deep/.el-image .el-image__inner {
          width: 120px;
          height: 120px;
          border: 1px solid #f8f8f9;
          margin-right: 20px;
        }
        /deep/.el-image .image-slot img {
          width: 120px;
          height: 120px;
          border: 1px solid #f8f8f9;
          margin-right: 20px;
        }
        .main_xqi {
          width: 80%;
          margin-left: 5px;
        }
        .main_upImg {
          /deep/ul {
            li {
              padding-left: 0;
            }
          }
          /deep/.el-upload-list--picture-card
            .el-upload-list__item:first-child {
            margin-left: 145px;
          }
        }
      }
    }
  }

  .mainor_pr {
    margin-left: 10px;
    margin-bottom: 10px;
  }
  .base_p {
    width: 80px;
  }
  .main_page_top {
    margin-top: 7px;
    margin-left: 10px;
    use {
      fill: $menuText;
    }
    &:hover {
      cursor: pointer;
      use {
        fill: $menuActiveText;
      }
    }
  }
}
.afterbox > ul > li {
  width: 20% !important;
}
</style>
